package com.youlu.campus.web.ca.controller;

import com.youkol.support.kaptcha.cache.KaptchaCacheResolver;
import com.youkol.support.kaptcha.cache.impl.RedisKaptchaCacheResolver;
import com.youkol.support.kaptcha.cache.impl.SessionKaptchaCacheResolver;
import com.youlu.campus.entity.VO.req.MyCaInfoVO;
import com.youlu.campus.web.ca.service.UserCaInfoService;
import com.yuelin.infrastructure.quantum.common.QResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;

@Slf4j
@RestController
public class QueryCaInfoController {

    @Autowired
    private UserCaInfoService userCaInfoService;

    @Autowired
    private RedisKaptchaCacheResolver kaptchaCacheResolver;



    private final String errmsg ="1、请检查输入的姓名是否和证书上一致\n"+
                                  "2、请检查证书编号字母是否带有空格\n"+
            "3、请检查证书编号字母大小写是否正确\n"+
            "4、若姓名中间有间隔点“ · ”，请务必输入才可以查询";
    /**
     * 用户在证书查询
     * @return
     */
    @PostMapping("/ca-app/my-ca-info")
    public QResult queryCaInf(@RequestBody MyCaInfoVO myCaInfoVO, BindingResult bindingResult, HttpServletRequest request) {
        if (bindingResult.hasErrors()) {
            return QResult.fail(bindingResult.getFieldError().getDefaultMessage());
        }
        log.info("用户 -> {} 查询证书 ->{} 验证码 - >{} 获取请求头 - >{}",myCaInfoVO.getUserName(),myCaInfoVO.getCertificateNo(), myCaInfoVO.getCaptcha(), request.getSession().getAttribute("CAMPUS-KAPTCHA-TOKEN"));
        try {
            boolean existKaptcha = kaptchaCacheResolver.validKaptcha(request, myCaInfoVO.getCaptcha());
            if(!existKaptcha){
                return QResult.fail(500,"亲,验证码输入错误,请重新输入");
            }
        }catch ( Exception e){
            log.info("用户 -> {} 查询证书 ->{} 验证码 - >{} ",myCaInfoVO.getUserName(),myCaInfoVO.getCertificateNo(),
                    myCaInfoVO.getCaptcha(), e);
            return QResult.fail(500,"验证码已过期,请重新输入");
        }

        try {
            return QResult.success(userCaInfoService.queryMyCaInfo(myCaInfoVO));
        }catch (Exception e){
           return QResult.fail(4004,errmsg);
        }
    }

//    @Autowired
//    DefaultKaptcha defaultKaptcha;

//    @GetMapping("/kaptcha")
//    public void kaptcha(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse)
//            throws Exception {
//        byte[] captchaChallengeAsJpeg = null;
//        ByteArrayOutputStream jpegOutputStream = new ByteArrayOutputStream();
//        try {
//            // 生产验证码字符串并保存到session中
//            String createText = defaultKaptcha.createText();
//            log.info("seesion code- > {}",createText);
//            httpServletRequest.getSession().setAttribute("verificationCode", createText);
//            // 使用生成的验证码字符串返回一个BufferedImage对象并转为byte写入到byte数组中
//            BufferedImage challenge = defaultKaptcha.createImage(createText);
//            ImageIO.write(challenge, "jpg", jpegOutputStream);
//        } catch (IllegalArgumentException e) {
//            httpServletResponse.sendError(HttpServletResponse.SC_NOT_FOUND);
//            return;
//        }
//
//        // 定义response输出类型为image/jpeg类型，使用response输出流输出图片的byte数组
//        captchaChallengeAsJpeg = jpegOutputStream.toByteArray();
//        httpServletResponse.setHeader("Cache-Control", "no-store");
//        httpServletResponse.setHeader("Pragma", "no-cache");
//        httpServletResponse.setDateHeader("Expires", 0);
//        httpServletResponse.setContentType("image/jpeg");
//        ServletOutputStream responseOutputStream = httpServletResponse.getOutputStream();
//        responseOutputStream.write(captchaChallengeAsJpeg);
//        responseOutputStream.flush();
//        responseOutputStream.close();
//    }

}
